import json
import os
from django.shortcuts import render
from django.http import JsonResponse
from django.views.decorators.http import require_GET, require_POST
from django.views.decorators.csrf import csrf_exempt
from django.conf import settings


def load_api_config():
    """加载API配置文件"""
    config_path = os.path.join(os.path.dirname(__file__), "api_config.json")
    try:
        with open(config_path, "r", encoding="utf-8") as f:
            return json.load(f)
    except FileNotFoundError:
        return {
            "api_info": {
                "title": "API文档",
                "version": "1.0.0",
                "description": "API配置文件未找到",
            },
            "categories": [],
            "data_types": {},
            "examples": [],
        }


def load_rules_content():
    """加载规则文档内容"""
    rules_path = os.path.join(
        os.path.dirname(__file__), "templates", "api_docs", "rules.html"
    )
    try:
        with open(rules_path, "r", encoding="utf-8") as f:
            content = f.read()
            # 提取body标签内的内容
            start_tag = "<body>"
            end_tag = "</body>"
            start_index = content.find(start_tag)
            end_index = content.find(end_tag)

            if start_index != -1 and end_index != -1:
                # 提取body内容，去掉body标签本身
                body_content = content[start_index + len(start_tag) : end_index]
                return body_content.strip()
            else:
                return content  # 如果没有找到body标签，返回全部内容
    except FileNotFoundError:
        return "<h1>规则文档未找到</h1><p>请检查rules.html文件是否存在。</p>"


def load_format_content():
    """加载格式文档内容"""
    # 格式文件路径
    formats_dir = os.path.join(settings.BASE_DIR, 'api_docs', 'format')
    input_format_path = os.path.join(formats_dir, 'format_input.md')
    output_format_path = os.path.join(formats_dir, 'format_output.md')

    input_content = ""
    output_content = ""

    try:
        with open(input_format_path, 'r', encoding='utf-8') as f:
            input_content = f.read()
    except FileNotFoundError:
        input_content = "# 输入格式文档未找到\n\n请检查 format_input.md 文件是否存在。"

    try:
        with open(output_format_path, 'r', encoding='utf-8') as f:
            output_content = f.read()
    except FileNotFoundError:
        output_content = "# 输出格式文档未找到\n\n请检查 format_output.md 文件是否存在。"

    return {
        'input_format_content': input_content,
        'output_format_content': output_content
    }

@require_GET
def api_docs_home(request):
    """API文档主页"""
    config = load_api_config()
    rules_content = load_rules_content()
    format_content = load_format_content()
    return render(
        request,
        "api_docs/index.html",
        {
            "config": json.dumps(config),
            "config_obj": config,
            "api_info": config.get("api_info", {}),
            "data_types": config.get("data_types", {}),
            "examples": json.dumps(config.get("examples", [])),
            "rules_content": rules_content,
            "input_format_content": format_content['input_format_content'],
            "output_format_content": format_content['output_format_content'],
        },
    )


@require_GET
def api_config_json(request):
    """返回API配置的JSON数据"""
    config = load_api_config()
    return JsonResponse(config)


@require_GET
def api_category_detail(request, category_id):
    """获取特定分类的API详情"""
    config = load_api_config()
    categories = config.get("categories", [])

    category = None
    for cat in categories:
        if cat.get("id") == category_id:
            category = cat
            break

    if not category:
        return JsonResponse({"error": "分类不存在"}, status=404)

    return JsonResponse(category)


@require_GET
def api_detail(request, category_id, api_id):
    """获取特定API的详细信息"""
    config = load_api_config()
    categories = config.get("categories", [])

    # 查找分类
    category = None
    for cat in categories:
        if cat.get("id") == category_id:
            category = cat
            break

    if not category:
        return JsonResponse({"error": "分类不存在"}, status=404)

    # 查找API
    api_info = None
    for api in category.get("apis", []):
        if api.get("id") == api_id:
            api_info = api
            break

    if not api_info:
        return JsonResponse({"error": "API不存在"}, status=404)

    return JsonResponse(api_info)


@require_GET
def config_editor(request):
    """API配置编辑器页面"""
    if not request.user.is_staff:
        return JsonResponse({"error": "权限不足"}, status=403)

    config = load_api_config()
    return render(
        request,
        "api_docs/config_editor.html",
        {"config_json": json.dumps(config, indent=2, ensure_ascii=False)},
    )


from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_POST


@csrf_exempt
@require_POST
def save_config(request):
    """保存API配置"""
    if not request.user.is_staff:
        return JsonResponse({"error": "权限不足"}, status=403)

    try:
        config_data = json.loads(request.body)
        config_path = os.path.join(os.path.dirname(__file__), "api_config.json")

        # 备份原配置
        backup_path = config_path + ".backup"
        if os.path.exists(config_path):
            import shutil

            shutil.copy2(config_path, backup_path)

        # 保存新配置
        with open(config_path, "w", encoding="utf-8") as f:
            json.dump(config_data, f, indent=2, ensure_ascii=False)

        return JsonResponse({"success": True, "message": "配置保存成功"})

    except json.JSONDecodeError:
        return JsonResponse({"error": "JSON格式错误"}, status=400)
    except Exception as e:
        return JsonResponse({"error": f"保存失败: {str(e)}"}, status=500)

import os
import zipfile
import io
from django.http import HttpResponse
from django.conf import settings

def download_language_template(request, language):
    """下载指定语言的模板文件"""
    # 语言映射
    language_map = {
        'python': {'folder': 'py', 'name': 'Python'},
        'javascript': {'folder': 'js', 'name': 'JavaScript'},
        'typescript': {'folder': 'ts', 'name': 'TypeScript'},
        'lua': {'folder': 'lua', 'name': 'Lua'}
    }

    if language not in language_map:
        return HttpResponse('Language not supported', status=400)

    lang_info = language_map[language]
    api_path = os.path.join(settings.BASE_DIR, 'static', 'api', lang_info['folder'])

    if not os.path.exists(api_path):
        return HttpResponse('Template not found', status=404)

    # 创建ZIP文件
    zip_buffer = io.BytesIO()

    with zipfile.ZipFile(zip_buffer, 'w', zipfile.ZIP_DEFLATED) as zip_file:
        # 递归添加目录下的所有文件
        for root, dirs, files in os.walk(api_path):
            for file in files:
                file_path = os.path.join(root, file)
                # 计算相对路径
                arcname = os.path.relpath(file_path, api_path)
                zip_file.write(file_path, arcname)

    zip_buffer.seek(0)

    response = HttpResponse(zip_buffer.getvalue(), content_type='application/zip')
    response['Content-Disposition'] = f'attachment; filename="{language}_template.zip"'
    return response


@require_GET
def map_editor(request):
    """地图编辑器页面"""
    # 加载TildeType枚举类型信息
    tile_types = {
        # 地形类型
        'flat': {'id': 0, 'name': '平地', 'category': 'terrain'},
        'hill': {'id': 1, 'name': '山丘', 'category': 'terrain'},
        'river': {'id': 2, 'name': '河流', 'category': 'terrain'},

        # 资源类型
        'gold': {'id': 11, 'name': '黄金', 'category': 'resource'},
        'energy': {'id': 12, 'name': '能源', 'category': 'resource'},
        'wood': {'id': 13, 'name': '木材', 'category': 'resource'},
        'stone': {'id': 14, 'name': '石材', 'category': 'resource'},

        # 基地类型
        'base': {'id': 99, 'name': '基地', 'category': 'building'}
    }

    return render(
        request,
        "api_docs/map_editor.html",
        {
            "tile_types": tile_types,
        },
    )


@csrf_exempt
@require_POST
def save_map(request):
    """保存地图数据"""
    try:
        map_data = json.loads(request.body)
        # 这里可以添加保存地图数据的逻辑
        # 例如保存到数据库或文件系统

        return JsonResponse({"status": "success", "message": "地图保存成功"})
    except Exception as e:
        return JsonResponse({"status": "error", "message": str(e)}, status=400)
